import React from 'react'
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
} from 'chart.js'
import { Line } from 'react-chartjs-2'

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
)

interface LineChartProps {
  data: {
    labels: string[]
    datasets: Array<{
      label: string
      data: number[]
      borderColor: string
      backgroundColor?: string
      fill?: boolean
      tension?: number
    }>
  }
  title?: string
  height?: number
  yAxisLabel?: string
  showLegend?: boolean
  showGrid?: boolean
  animate?: boolean
}

const LineChart: React.FC<LineChartProps> = ({
  data,
  title,
  height = 300,
  yAxisLabel,
  showLegend = true,
  showGrid = true,
  animate = true
}) => {
  const options = {
    responsive: true,
    maintainAspectRatio: false,
    animation: animate ? {
      duration: 750,
      easing: 'easeInOutQuart' as const
    } : false,
    plugins: {
      legend: {
        display: showLegend,
        position: 'top' as const,
        labels: {
          usePointStyle: true,
          padding: 20,
          font: {
            size: 12
          }
        }
      },
      title: {
        display: !!title,
        text: title,
        font: {
          size: 16,
          weight: 'bold' as const
        },
        padding: {
          top: 10,
          bottom: 30
        }
      },
      tooltip: {
        mode: 'index' as const,
        intersect: false,
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        titleColor: '#fff',
        bodyColor: '#fff',
        borderColor: '#ddd',
        borderWidth: 1,
        cornerRadius: 6,
        displayColors: true,
        callbacks: {
          label: function(context: any) {
            let label = context.dataset.label || ''
            if (label) {
              label += ': '
            }
            if (context.parsed.y !== null) {
              // 根据数据类型格式化显示
              if (yAxisLabel?.includes('%')) {
                label += context.parsed.y.toFixed(1) + '%'
              } else if (yAxisLabel?.includes('MB') || yAxisLabel?.includes('GB')) {
                label += formatBytes(context.parsed.y)
              } else {
                label += context.parsed.y.toLocaleString()
              }
            }
            return label
          }
        }
      }
    },
    interaction: {
      mode: 'nearest' as const,
      axis: 'x' as const,
      intersect: false
    },
    scales: {
      x: {
        display: true,
        grid: {
          display: showGrid,
          color: 'rgba(0, 0, 0, 0.1)'
        },
        ticks: {
          font: {
            size: 11
          },
          maxTicksLimit: 10
        }
      },
      y: {
        display: true,
        grid: {
          display: showGrid,
          color: 'rgba(0, 0, 0, 0.1)'
        },
        ticks: {
          font: {
            size: 11
          },
          callback: function(value: any) {
            if (yAxisLabel?.includes('%')) {
              return value + '%'
            } else if (yAxisLabel?.includes('MB') || yAxisLabel?.includes('GB')) {
              return formatBytes(value)
            }
            return value.toLocaleString()
          }
        },
        title: {
          display: !!yAxisLabel,
          text: yAxisLabel,
          font: {
            size: 12,
            weight: 'bold' as const
          }
        }
      }
    },
    elements: {
      point: {
        radius: 3,
        hoverRadius: 6,
        borderWidth: 2
      },
      line: {
        borderWidth: 2
      }
    }
  }

  // 格式化字节数
  const formatBytes = (bytes: number) => {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
  }

  return (
    <div style={{ height: `${height}px`, width: '100%' }}>
      <Line data={data} options={options} />
    </div>
  )
}

export default LineChart
